package com.bq.gametrade.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.service.SmsReceiver;
import com.bq.gametrade.utils.CheckUtils;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.view.TimeButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegisteredActivity extends BaseActivity implements View.OnClickListener {


    private ImageView back;
    private Button btnGetCode;
    private Button btnConfirm;
    private EditText etUserAccount,etPhoneNumber,etPassword,etValidationCode;
    private Activity activity;

    private SmsReceiver smsReceiver;

    private ImageView btnShowPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.login_bg));

        }
        setContentView(R.layout.activity_registered);
        activity = this;
        initView();
//        readSms();
    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        etUserAccount = serchViewById(R.id.ed_userAccount);
        etPhoneNumber = serchViewById(R.id.ed_phoneNumber);
        etPassword = serchViewById(R.id.ed_userPassword);
        btnGetCode = serchViewById(R.id.btn_getCode);
        btnGetCode.setOnClickListener(this);
        etValidationCode = serchViewById(R.id.et_verificationCode);
        btnConfirm = serchViewById(R.id.btn_registered);
        btnConfirm.setOnClickListener(this);
        btnShowPassword = serchViewById(R.id.bt_showPassword);
        btnShowPassword.setOnClickListener(this);

    }

    private boolean isShow = true;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.bt_showPassword:
                    isShow = !btnShowPassword.isSelected();
                if(isShow){
                   btnShowPassword.setSelected(true);
                    btnShowPassword.setBackgroundResource(R.mipmap.icon_eyes_open);
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else {
                    btnShowPassword.setSelected(false);
                    btnShowPassword.setBackgroundResource(R.mipmap.icon_eyes_close);
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.btn_getCode:
//                if(TextUtils.isEmpty(etUserAccount.getText().toString())){
//                    toastShow("用户名没有输入");
//                    return;
//                }
//                if(etUserAccount.getText().toString().length()<5){
//                    toastShow("用户名不能少于5位");
//                    return;
//                }
//                if(etUserAccount.getText().toString().length()>20){
//                    toastShow("用户名不能多余20位");
//                    return;
//                }
                if(!CheckUtils.isMobile(etPhoneNumber.getText().toString())){
                    toastShow("手机号码不正确");
                    return;
                }
                if(TextUtils.isEmpty(etPassword.getText().toString())){
                    toastShow("密码未输入");
                    return;
                }
                if(etPassword.getText().toString().length()<6){
                    toastShow("密码位数不能少于6位");
                    return;
                }
                if(NetworkUtils.isNetworkAvailable(activity)){
                    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                        checkSmsPermission();
                    }else {
                        sendCode();
                        etValidationCode.requestFocus();
                    }

                }else {
                    toastShow("请检查您的网络");
                }
                break;
            case R.id.btn_registered:
//                if(TextUtils.isEmpty(etUserAccount.getText().toString())){
//                    toastShow("用户名没有输入");
//                    return;
//                }
//                if(etUserAccount.getText().toString().length()<5){
//                    toastShow("用户名不能少于5位");
//                    return;
//                }
//                if(etUserAccount.getText().toString().length()>20){
//                    toastShow("用户名不能多余20位");
//                    return;
//                }
                if(!CheckUtils.isMobile(etPhoneNumber.getText().toString())){
                    toastShow("手机号码不正确");
                    return;
                }
                if(TextUtils.isEmpty(etPassword.getText().toString())){
                    toastShow("密码未输入");
                    return;
                }
                if(etPassword.getText().toString().length()<6){
                    toastShow("密码位数不能少于6位");
                    return;
                }
                if(NetworkUtils.isNetworkAvailable(activity)){
                    toRegistered();
                }else {
                    toastShow("请检查您的网络");
                }
                break;
        }
    }




    @Override
    protected void performHandleMessage(Message msg) {
        super.performHandleMessage(msg);
        if (msg.what == 1)
        {
            etValidationCode.setText(msg.obj.toString());
        }
    }

    private void readSms(){
        smsReceiver = new SmsReceiver(RegisteredActivity.this,mHandler);
        IntentFilter  filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(smsReceiver,filter);
    }

    private void sendCode(){
        /**
         * 注册时验证码类型：codeType = 0;
         */
        String codeType = "0";
        Map<String,String> params = new HashMap<>();
        params.put("tel",etPhoneNumber.getText().toString());
        params.put("codeType",codeType);
        showSpotsDialog("正在发送验证码···");
        VRHttp.sendRequest(RegisteredActivity.this, HttpLink.GET_VERIFICATIONCODE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();

                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("已发送！请查看");
                        TimeButton timeButton = new TimeButton(RegisteredActivity.this, 60 * 1000, 1000, btnGetCode);
                        timeButton.start();
                    } else if (bean.status.equals("1")) {
                        toastShow("手机号码已注册！");
                    }
                } else {
                    toastShow("获取验证码失败");
                }
            }
            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("发送验证码失败");
                closeSpotsDialog();
            }
        });
    }

    private void toRegistered(){
        Map<String,String> params = new HashMap<>();
        params.put("username",etPhoneNumber.getText().toString());
        params.put("password", MD5Util.md5(etPassword.getText().toString()));
        params.put("nickname","");
        params.put("tel",etPhoneNumber.getText().toString());
        params.put("code",etValidationCode.getText().toString());
        showSpotsDialog();
        VRHttp.getResponse(activity, HttpLink.USER_REGISTERED_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                try {
                    JSONObject object = new JSONObject(response.toString());
                    String status = object.getString("status");
                    if(status.equals("0")){
                        toastShow("注册成功，请登录");
                        startActivity(new Intent(RegisteredActivity.this,LoginActivity.class));
                        finish();
                    }else if (status.equals("1")){
                        toastShow("验证码不正确");
                    }
                    else if (status.equals("2")){
                        toastShow("手机号已被注册");
                    }else {
                        String message = object.getString("message");
                        toastShow(new String(Base64.decode(message.getBytes(), 0, message.length(), Base64.DEFAULT)));
                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("注册失败");
                closeSpotsDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(smsReceiver !=null){
            unregisterReceiver(smsReceiver);
        }

    }


    private static final int REQUEST_PERM = 151;

    /***
     * 动态授权
     */
    private void checkSmsPermission(){

        if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{
                    Manifest.permission.RECEIVE_SMS,

            };
            ActivityCompat.requestPermissions(this,mPermissionList,REQUEST_PERM);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERM: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    sendCode();
                    readSms();

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    sendCode();
                }
                return;
            }
        }
    }
}
